define(["../common"], function() {
	
	var $form = $("#form_info");
	var formCfg = {
		fields: {
			realName: "真实姓名: length[~20]",
			street: "地址: length[~80]"
		}
	};
	
	requirePlugin(["datepicker"]);
	requirePlugin(["validator"],function() {
		$form.validator(formCfg);
	});
	
	// 初始化表单值
	$.getJSON(g_userDomain + "/member/info/json", function(data) {
		if (data.status !== 0) {
			$(this).failMsg(data.message);
			return;
		}
		var member = data.result;
		$("#name").html(member.name);
		$(":radio[name=sex][value='"+ member.sex +"']").parent().click();
		$("#realName").val(member.realName);
		
		var link = g_userDomain + "/member/mobile";
		if (member.mobile) {
			$("#mobile").html(member.mobile + '<a href="' + link + '" style="margin-left:10px;">修改</a>');
		} else {
			$("#mobile").html('<a href="' + link + '">绑定</a>');
		}
		
		link = g_userDomain + "/member/email";
		if (member.email) {
			$("#email").html(member.email + '<a href="' + link + '" style="margin-left:10px;">修改</a>');
		} else {
			$("#email").html('<a href="' + link + '">绑定</a>');
		}
		
		if (member.birthday) {
			var date = new Date();
			date.setTime(member.birthday);
			$("#birthday").val(member.birthday);
			$("#birthdayPicker").val(date.format("yyyy-MM-dd"));
		}
		
		$("#regionId").val(member.regionId);
		if (member.regionId) {
			loadRegions(member.regionId);
		} else {
			Region.locating(function(region) {
				loadRegions(region.regionId);
			});
		}
		
		$("#street").val(member.street);
	});
	
	$("a.checkbox").click(function() {
		$(this).trigger('check');
		return false;
	});
	
	// 提交完成表单
	$form.on('valid.form', function(e, form) {
		if (!$form.lock()) return;
		
		$form.loadMsg("正在保存...");
		$("#birthday").val($("#birthdayPicker").val().toTimestamp());
		$.post(g_userDomain + "/member/infoDo/json", $form.serialize(), function(data){
			if (data.status !== 0) {
				$form.failMsg(data.message);
				return;
			}
			$form.infoMsg("保存成功");
			
			$form.hide();
			$form.next().show();
		});

	});
	
	// 完成
	$("#btn_submit").click(function() {
		$form.trigger('validate');
		return false;
	});	
	
	function loadRegions(regionId) {
		require(["region"], function() {
			$("#regions").regionsSelect({
				value: regionId, 
				onLoad: function($select) {
					$select.attr("data-rule","地区: required;");
					$select.addClass("form-control");
					$select.css({width: "48%",float: "left","margin-right": "1%"});
				},
				onSelect: function($select) {
					$("#regionId").val($select.val());
				}
			});
		});
	}
	
});